<?php


namespace App\Http\Controllers\Upload;


use App\Common\Exception\ErrorException;
use App\Common\Utils\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Request\Upload\downloadRequest;
use App\Http\Request\Upload\ExportProductsRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class DownloadController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
//        $this->middleware('auth');
    }

    public function downloadzip(downloadRequest $request)
    {

        try
        {
            if(!$request->isValid()){
                throw new \Exception($request->getErrMsg());
            }else{

                $requestData = $request->getData();

                $saved_file = $requestData['zipname'] .'.zip';
                $zip_file = public_path('uploads/download').'/'.$saved_file;
                if (file_exists($zip_file)){
                    return JsonResponse::get($saved_file);
                }
                $user_id = auth()->user()->user_id;
                $newPath = public_path('uploads/download').'/'.$user_id;
                if(!is_readable($newPath)) {
                    mkdir($newPath);
                }

                foreach ($requestData['resources'] as $resource) {
                    $file_url = $resource['fileurl'] ?? $resource['url'];
                    $file_name = $resource['filename'] ?? $resource['file_name'];
                    $relative = explode('uploads',$file_url);
                    $relativefile = public_path('uploads'.$relative[1]);
                    if(file_exists($relativefile)){
                        copy($relativefile,$newPath.'/'.$file_name);
                    }

                }

                $zip = new \ZipArchive();
                if ($zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === TRUE) {
                    $path = public_path('uploads/download');
                    $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
                    foreach ($files as $name => $file) {
                        // 我们要跳过所有子目录
                        if (file_exists($file)) {
                            if (!$file->isDir()) {
                                $filePath = $file->getRealPath();
                                $zip->addFile($filePath,basename($filePath));
                            }
                        } else {
                            throw new ErrorException('该目录不存在或被删除');
                        }

                    }

                }

                @$zip->close();
                $this->deldir($newPath.'/');
                return JsonResponse::get($saved_file);


            }
        }
        catch(\Exception $e)
        {
            return $this->error($e);
        }
    }


    public function downloadzip2(downloadRequest $request)
    {

        try
        {


                $requestData2 = $request->getData();
                $requestData = [];
                foreach($requestData2['resources'] as $k=>$v){
                    foreach($v['materials'] as $k2=>$v2){
                        $requestData[] = $v2;
                    }
                }

                $saved_file = '公开课'.auth()->user()->id.'.zip';
                $zip_file = public_path('uploads/download').'/'.$saved_file;
                if (file_exists($zip_file)){
                    return JsonResponse::get($saved_file);
                }
                $user_id = auth()->user()->user_id;
                $newPath = public_path('uploads/download').'/'.$user_id;
                if(!is_readable($newPath)) {
                    mkdir($newPath);
                }

                foreach ($requestData as $resource) {
                    $file_url = $resource['fileurl'] ?? $resource['url'];
                    $file_name = $resource['filename'] ?? $resource['file_name'];
                    $relative = explode('uploads',$file_url);
                    $relativefile = public_path('uploads'.$relative[1]);
                    if(file_exists($relativefile)){
                        copy($relativefile,$newPath.'/'.$file_name);
                    }

                }

                $zip = new \ZipArchive();
                if ($zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === TRUE) {
                    $path = public_path('uploads/download');
                    $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
                    foreach ($files as $name => $file) {
                        // 我们要跳过所有子目录
                        if (file_exists($file)) {
                            if (!$file->isDir()) {
                                $filePath = $file->getRealPath();
                                $zip->addFile($filePath,basename($filePath));
                            }
                        } else {
                            throw new ErrorException('该目录不存在或被删除');
                        }

                    }



                @$zip->close();
                $this->deldir($newPath.'/');
                return JsonResponse::get($saved_file);


            }
        }
        catch(\Exception $e)
        {
            return $this->error($e);
        }
    }

    public function downloadpdf()
    {
        $realurl = request()->get('url') ?? '';
        if ($realurl == ''){
            throw new ErrorException('文件路径不正确');
        }
        $url = $realurl;
        $real_name = request()->get('filename');

        $headers=[
            "Content-Disposition"=>"attachment; filename=".$real_name,
            "Content-Transfer-Encoding"=>" binary",
            "Content-Type"=> "application/pdf"
        ];

        return response()->download($url,$real_name,$headers)->deleteFileAfterSend();
    }

    public function excelDownload(Request $request)
    {
        $id = $request->route('id');
        $filename = $request->get('filename','');
        $filekey = $request->get('filekey','');
        if ($id == 1){
           $filename = "学校团队报名学生名单.xlsx";
           $downFileName = "imports_student.xlsx";
           $url = public_path("download/templates/$downFileName");
        }
        if ($id == 2){
            $url = public_path('download/excel/'.$filekey);
        }
        if ($id == 3){
            $filename = "专家批量导入.xlsx";
            $downFileName = "imports_expert.xlsx";
            $url = public_path("download/templates/$downFileName");
        }
        if ($id == 4){
            $filename = "学校个人报名学生名单.xlsx";
            $downFileName = "imports_student2.xlsx";
            $url = public_path("download/templates/$downFileName");
        }
        if ($filename == ''){
            throw new ErrorException('文件名不能为空');
        }
        $headers=[
            "Content-Disposition"=>"attachment; filename=".$filename,
            "Content-Transfer-Encoding"=>" binary",
            "Content-Type"=> 'application/vnd.ms-excel'
        ];
        return response()->download($url,$filename,$headers);
    }

    public function excelExport()
    {
        $filename = Request()->get('filename');
        if ($filename == ''){
            throw new ErrorException('文件名不能为空');
        }
        $headers=[
            "Content-Disposition"=>"attachment; filename=".$filename,
            "Content-Transfer-Encoding"=>" binary",
            "Content-Type"=> 'application/vnd.ms-excel'
        ];
        return response()->download(public_path("download/exports/$filename"),'专家账号信息列表.xlsx',$headers)->deleteFileAfterSend();
    }

    private function deldir($path){
        //如果是目录则继续
        if(is_dir($path)){
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach($p as $val){
                //排除目录中的.和..
                if($val !="." && $val !=".."){
                    //如果是目录则递归子目录，继续操作
                    if(is_dir($path.$val)){
                        //子目录中操作删除文件夹和文件
                        $this->deldir($path.$val.'/');
                        //目录清空后删除空文件夹
                        @rmdir($path.$val.'/');
                    }else{
                        //如果是文件直接删除
                        unlink($path.$val);
                    }
                }
            }
        }
    }

    public function downProduct(Request $request)
    {
        $id = $request->route('id');

        /** @var \App\Services\Backend\Activity\ActivityParticipantService $activityParticipantService */
        $activityParticipantService = app('activityParticipantService');
        $activityParticipant = $activityParticipantService->getCore($id);
        $activityParticipant = $activityParticipant->toArray();

        if(!is_readable(public_path('uploads/download'))) {
            mkdir(public_path('uploads/download'));
        }

        $saved_file = $activityParticipant['names'].'('.$activityParticipant['entry_name'].')'.'.zip';
        $zip_file = public_path('uploads/download').'/'.$saved_file;

        $newPath = public_path('uploads/download').'/'.$activityParticipant['names'].'('.$activityParticipant['entry_name'].')';
        if(!is_readable($newPath)) {
            mkdir($newPath);
        }

        /** @var \App\Services\Backend\Activity\ActivityEntryService $activityEntryService */
        $activityEntryService = app('activityEntryService');
        $entrys = $activityEntryService->getAllCore(['participant_id' => $id]);
        $entrys = $entrys->toArray();

        foreach ($entrys as $entry) {
            $relative = explode('uploads',$entry['entry_url']);
            $relativefile = public_path('uploads'.$relative[1]);
            if(file_exists($relativefile)){
                copy($relativefile,$newPath.'/'.$entry['entry_originalname']);
            }
        }

        $zip = new \ZipArchive();
        if ($zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === TRUE) {
//            $path = public_path('uploads/download');
            $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($newPath));
            foreach ($files as $name => $file) {
                // 我们要跳过所有子目录
                if (file_exists($file)) {
                    if (!$file->isDir()) {
                        $filePath = $file->getRealPath();
                        $zip->addFile($filePath, basename($filePath));
                    }
                } else {
                    throw new ErrorException('该目录不存在或被删除');
                }

            }


            @$zip->close();
            $this->deldir($newPath.'/');
            @rmdir($newPath.'/');

            $headers=[
                "Content-Disposition"=>"attachment; filename=".$saved_file,
                "Content-Transfer-Encoding"=>" binary",
                "Content-Type"=> 'application/x-zip-compressed'
            ];
            return response()->download($zip_file,$saved_file,$headers);
        }
    }

    public function exportProducts(ExportProductsRequest $request)
    {

        try
        {
            if(!$request->isValid()){
                throw new \Exception($request->getErrMsg());
            }else{

                $requestData = $request->getData();
                $activity_name = $requestData['activity_name'];
                $proj_name = '';

                /** @var \App\Services\Backend\Activity\ActivityParticipantService $activityParticipantService */
                $activityParticipantService = app('activityParticipantService');

                $filters = [];
                $sorts = ["id" => "ASC"];
                if($requestData['type'] == '1'){
                    $filters[] = ['activity_id', '=', $requestData['activity_id']];
                    $filters[] = ['entry_upload_status', '=', '1'];
                }elseif ($requestData['type'] == '2'){
                    $filters[] = ['project_id', '=', $requestData['activity_id']];
                    $filters[] = ['entry_upload_status', '=', '1'];

                    /** @var \App\Services\Backend\Activity\ProjectService $projectService */
                    $projectService = app('projectService');
                    $project = $projectService->getCore($requestData['activity_id']);
                    $proj_name = $project->proj_name;
                }

                $root = public_path('uploads/download');
                if(!is_readable($root)) {
                    mkdir($root);
                }

                $saved_file = $proj_name == '' ? $activity_name.'的作品信息.zip' : $activity_name.'('.$proj_name.')的作品信息.zip';
                $zip_file = public_path('uploads/download').'/'.$saved_file;

                $newPath = $proj_name == '' ? $activity_name.'的作品信息' : $activity_name.'('.$proj_name.')的作品信息';
                $newPath = public_path('uploads/download').'/'.$newPath;
                if(!is_readable($newPath)) {
                    mkdir($newPath);
                }

                $participants = $activityParticipantService->getAllCore($filters,$sorts);
                $participants = $participants->toArray();
                if(empty($participants)){
                    throw new ErrorException('尚未上传作品');
                }
                foreach ($participants as $participant){
                    $participantPath = $newPath.'/'.$participant['names'].'('.$participant['entry_name'].')';
                    if(!is_readable($participantPath)) {
                        mkdir($participantPath);
                    }

                    /** @var \App\Services\Backend\Activity\ActivityEntryService $activityEntryService */
                    $activityEntryService = app('activityEntryService');
                    $entrys = $activityEntryService->getAllCore(['participant_id' => $participant['id']]);
                    $entrys = $entrys->toArray();

                    foreach ($entrys as $entry) {
                        $relative = explode('uploads',$entry['entry_url']);
                        $relativefile = public_path('uploads'.$relative[1]);
                        if(file_exists($relativefile)){
                            copy($relativefile,$participantPath.'/'.$entry['entry_originalname']);
                        }
                    }
                }

                $root = str_replace('\\', '/', $root);
                $zip = new \ZipArchive();
                if ($zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === TRUE) {
                    $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($newPath));
                    foreach ($files as $name => $file) {
                        $file = str_replace('\\', '/', $file);
                        if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                            continue;
                        if (is_dir($file)) {
                            $zip->addEmptyDir(str_replace($root . '/', '', $file . '/'));
                        } elseif(is_file($file)){
                            $zip->addFromString(str_replace($root . '/', '', $file), file_get_contents($file));
                        }
                    }

                    @$zip->close();
                    $this->deldir($newPath.'/');
                    @rmdir($newPath.'/');

                    return JsonResponse::get($saved_file);
                }
            }
        }
        catch(\Exception $e)
        {
            return $this->error($e);
        }
    }

    public function downloadActivityZipRes(Request $request)
    {
        $id = intval($request->get('id',''));
        $type = $request->get('type','');
        if ($id == 0){
            throw new ErrorException('活动id不能为空');
        }
        if ($type == ''){
            throw new ErrorException('type不能为空');
        }

        $filename = '';
        $fileurl = '';
        if($type == '1'){
            /** @var \App\Services\Backend\Activity\ActivityService $activityService */
            $activityService = app('activityService');

            $activity = $activityService->getCore($id);
            $filename = $activity->intro_res_name;
            $fileurl = $activity->intro_res_content;
        }elseif ($type == '2'){
            /** @var \App\Services\Backend\Activity\ProjectService $projectService */
            $projectService = app('projectService');

            $project = $projectService->getCore($id);
            $filename = $project->intro_res_name;
            $fileurl = $project->intro_res_content;
        }
        $url = public_path($fileurl);

        Log::info($filename);
        $headers=[
            "Content-Disposition"=>"attachment; filename=".$filename,
            "Content-Transfer-Encoding"=>" binary",
            "Content-Type"=> 'application/x-zip-compressed'
        ];
        return response()->download($url,$filename,$headers);
    }
}
